<template>
    <div class="common-layout">
      <div class="login">
        <h2 class="title" style="color: white;">{{ isLogin ? '登录' : '注册' }}</h2>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="isLogin ? loginRules : registerRules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="用户名" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入用户名" @focus="onUsernameFocus" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" :type="isLogin ? 'password' : 'text'" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" v-if="!isLogin">
              <el-input v-model="ruleForm.confirmPassword" :type="isLogin? 'password' : 'text'" placeholder="请输入确认密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">{{ isLogin ? '登录' : '注册' }}</el-button>
          </el-form-item>
        </el-form>
        <div class="footer">
          <button @click="toggleForm">{{ isLogin ? '去注册' : '去登录' }}</button>
        </div>
      </div>
    </div>
</template>
  
<script>
import { reactive, ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import axios from 'axios';
import router from '@/router';

  
export default {
    components: {
      ElForm,
      ElFormItem,
      ElInput,
      ElButton
    },
    setup() {
      const validateConfirmPassword = (rule, value, callback) => {
          const trimmedValue = ruleForm.confirmPassword.trim(); // 去除确认密码输入值的两端空格
          const trimmedPassword = ruleForm.password.trim(); // 去除密码输入值的两端空格
          
          if (trimmedValue!== trimmedPassword) {
            callback();
            ElMessage.error('请保证两次密码一样');
          } else {
            ElMessage({type: 'success', message: '注册成功',})
          }
      };
      const ruleFormRef = ref(null);
      const ruleForm = reactive({
        name: '',
        password: '',
        confirmPassword: ''
      });

      const newUser = reactive({
        name: '',
        password: ''
      });
      const existingUser = reactive({
        name: ""
      })
      const newUser1 = {
        name: "",
        password: "",
      };
      const isLogin = ref(true);
      const userlist = ref([]);
      const loginRules = {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度 3 到 10', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 10, message: '长度 4 到 10', trigger: 'blur' },
        ]
      };
      const registerRules = {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度 3 到 10', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 10, message: '长度 4 到 10', trigger: 'blur' },
        ]
        ,
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    
      const mounted = () => {
        axios.get('users.json')
          .then(res => {
            userlist.value = res.data.userslist;
          })
          .catch(err => {
            console.error('请求用户数据出现错误：', err);
          });
      };
      
      const generateToken = (username) => {
        return username + ':' + Date.now();
      };
      var token;
      var user;
      const onUsernameFocus = () => {
        token = sessionStorage.getItem('token');
        console.log('Token:', token);
        if (token) {
          const parts = token.split(':');
          if (parts.length === 2) {
            newUser.name = parts[0];
            newUser.password = parts[1];
            existingUser.name = parts[0];
          }
          console.log('newuser', newUser);
        }
      };
      // 
      const submitForm = () => {
        ruleFormRef.value.validate((valid) => {
          if (valid) {
            user = userlist.value.find(u => u.name === ruleForm.name && u.password === ruleForm.password);
          // 登录
            if (isLogin.value) {
              if (user) {
                if (!newUser.name) {
                  sessionStorage.setItem('username', newUser.name);
                } else {
                  sessionStorage.setItem('username', newUser1.name);
                }
                sessionStorage.setItem('username',user.name)
                sessionStorage.setItem('password',user.password)
                router.push('/');
                alert('登录成功');
              } else {
                alert('用户名或密码错误');
              }
            } else {
              // 注册
                newUser1.name = ruleForm.name;
                newUser1.password = ruleForm.password;
                if (newUser1.password != ruleForm.confirmPassword) {
                    // alert('确认密码与密码不一致，请重新输入');
                    return; // 直接返回，终止注册流程
                }
                if (userlist.value.some(u => u.name === newUser1.name)) {
                    alert('用户名已存在，请选择其他用户名');
                } else {
                    userlist.value.push(newUser1);
                    const token = generateToken(newUser1.name);
                    sessionStorage.setItem('token', token);
                    sessionStorage.setItem('username', newUser1.name);
                    sessionStorage.setItem('password', newUser1.password);

                    console.log(newUser1);
                    alert('注册成功');
                    isLogin.value = true; // 切换回登录表单
                }
            }
          }
        });
        ruleFormRef.value.validateField('confirmPassword');
        
      };


      const toggleForm = () => {
        isLogin.value =!isLogin.value;
        ruleForm.name = '';
        ruleForm.password = '';
        ruleForm.confirmPassword = ''; // 同时清空确认密码
        ruleFormRef.value.resetFields();
      };
      mounted();

      return {
        ruleFormRef,
        ruleForm,
        loginRules,
        registerRules,
        submitForm,
        toggleForm,
        isLogin,
        onUsernameFocus,
        newUser,
        ElMessage,
      };
    },
  };
</script>

<style setup>
    .el-form-item__label {
        color: white !important;
    }
</style>

<style scoped>
.common-layout {
    background: url(../../images/login.png) no-repeat center;
    width: 100%;
    height: 100vh;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
}
  
.login {
    width: 350px;
    display: flex;
    align-items: center;
    flex-direction: column;
    background-color: #aa999981;
    border-radius: 20px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(5px) saturate(0.5);
    border-radius: 13px;
    border: 1px solid rgba(255, 255, 255, 0.15);
    padding: 40px 60px;
    justify-content: center;
    flex-direction: column;
    font-weight: 300;
}
  
.title {
    font-size: 28px;
    margin-bottom: 20px;
    color: #333;
}
  
.el-form-item {
    margin-bottom: 15px;
}
  
.el-input__inner {
    height: 40px;
    border-radius: 20px;
    border: 1px solid #ccc;
}
  
.el-input__inner:focus {
    border-color: #007bff;
    box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
  
.el-button {
    height: 40px;
    border-radius: 20px;
    background-color: #007bff;
    color: #fff;
}
  
.el-button:hover {
    background-color: #0056b3;
}
  
.footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin-top: 20px;
}
  
  
input[type="checkbox"] {
    width: 20px;
    height: 20px;
    margin-right: 5px;
}
  
button {
    border: none;
    background: none;
    color: #007bff;
    font-size: 14px;
    cursor: pointer;
}
  
button:cover {
  
    border: none;
    background: none;
    color: #007bff;
    font-size: 14px;
    cursor: pointer;
    margin-right: auto;
}  
</style>